-- FUNCTION: public.widget_BarChart_Pharmacy_FrequentlyBroughtProducts(date, text, integer)

-- DROP FUNCTION public."widget_BarChart_Pharmacy_FrequentlyBroughtProducts"(date, text, integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_Pharmacy_FrequentlyBroughtProducts"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;

begin
create  Temp TABLE temp_table 
( ddate date, 
  dname text,
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";

raise notice 'filtervalue %', filtervalue;

--fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;

for f in SELECT generate_series("fromDate"-filtervalue, "fromDate"+filtervalue,  intervaldata) weeks
    loop 
	raise notice 'fromdate %', "fromDate"-filtervalue;
	raise notice 'todate %', "fromDate"+filtervalue;
	insert into temp_table (ddate,dname,countdata)

------------------------
	with saleData as (
	select PP."PharmacyProductId", count(PP."PharmacyProductId") "Count", PP."ProductName",PP."GenericName",ci."Name" "CategoryName",sum(PPD."Quantity") 
from "PharmacyPurchaseHeader" PH
		join "Supplier" s on s."SupplierId"=ph."SupplierId"
		join "PharmacyPurchaseDetail" ppd on ppd."PharmacyPurchaseHeaderId" = ph."PharmacyPurchaseHeaderId"
		join "PharmacyProduct" pp on pp."PharmacyProductId" = ppd."PharmacyProductId"
		join "LookupValue" ci on ci."LookupValueId"=pp."CategoryId"
		join "Account" A on A."AccountId"=ph."CreatedBy"
		join "Role" R on R."RoleId"=A."RoleId"
		left join "PharmacyPurchaseReturnHeader" pr on pr."PharmacyPurchaseHeaderId" = PH."PharmacyPurchaseHeaderId"
	where   PH."CreatedDate"::date >= f.weeks::text::date and PH."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date  
	--       case when "fromDate" is null then 1=1 else PH."BillDate"::date >= "fromDate" end 
	-- 	and case when "toDate" is null then 1=1 else PH."BillDate"::date <= "toDate" end 
	group by PP."PharmacyProductId",PP."ProductName",PP."GenericName",ci."Name" 
order by "Count"  desc limit 10
	) 
	select f.weeks, sd."ProductName" ,sd."Count"
	from saleData sd  ;
  
end loop;
	RETURN QUERY
	
	select A.ddate,A.dname,A.countdata from temp_table A 
	order by A.countData desc
	limit "displayCount";
	drop table temp_table;
	--drop table temp_date_table;				
	
END;
$BODY$;

ALTER FUNCTION public."widget_BarChart_Pharmacy_FrequentlyBroughtProducts"(date, text, integer)
    OWNER TO postgres;
